/*

*/
#ifndef SSD1306_H
#define SSD1306_H
#include <Arduino.h>
#include <U8x8lib.h>

#include "component_ultrasonic.h"
#include "component_dht11.h"

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif

U8X8_SSD1306_128X64_NONAME_HW_I2C u8x8(/* reset=*/U8X8_PIN_NONE);

float previous_temperature, previous_humidity;
String result_dht11_t, result_dht11_h;
String result_distance;

long previousMillis_display;
const int interval_display = 1000;

void setup_ssd1306()
{

  u8x8.begin();
  u8x8.setPowerSave(0);

  u8x8.setFont(u8x8_font_chroma48medium8_r);
  u8x8.drawString(0, 1, "MiniCar");
  delay(1000);
  // u8x8.setFont(u8x8_font_pxplustandynewtv_r); //稍大粗体
  // u8x8.drawString(0, 1, "MiniCar");
  // u8x8.setFont( u8x8_font_pxplusibmcga_r);//稍大粗体
  //  u8x8.drawString(0, 1, "MiniCar");
  // u8x8.setFont(u8x8_font_px437wyse700a_2x2_r);  //大粗体
  // u8x8.drawString(0, 1, "MiniCar");
  // delay(1000);


  dht11_on();
  
  previous_temperature = temperature;
  previous_humidity = humidity;
  result_dht11_t = "T" + String(temperature, 1) + "C";
  result_dht11_h = "H " + String(humidity, 1) + "%";
  u8x8.drawString(0, 1, result_dht11_t.c_str());
  u8x8.drawString(0, 3, result_dht11_h.c_str());
  double *distances = HCSR04.measureDistanceCm(); // read distance
  distance = distances[0];
  result_distance = "D " + String(distance, 1) + "cm";
  u8x8.drawString(0, 6, result_distance.c_str());
  u8x8.refreshDisplay(); // only required for SSD1606/7
}

void loop_ssd1306()
{
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis_display >= interval_display)
  {
    previousMillis_display = currentMillis;
    dht11_on();
    if (temperature != previous_temperature)
    {
      previous_temperature = previous_temperature;
      previous_humidity = humidity;
      result_dht11_t = "T " + String(temperature, 1) + "C";
      result_dht11_h = "H " + String(humidity, 1) + "%";
      u8x8.drawString(0, 1, result_dht11_t.c_str());
      u8x8.drawString(0, 3, result_dht11_h.c_str());
    };
    result_distance = "D " + String(distance, 1) + "cm";
    u8x8.drawString(0, 6, result_distance.c_str());
  }
}

#endif /* SSD1306_H */